package xyz.lne.researchgroupmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.catalina.User;
import org.apache.catalina.mbeans.MBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import xyz.lne.researchgroupmanage.controller.request.ResearchRequest;
import xyz.lne.researchgroupmanage.controller.request.UserApplyResearchRequest;
import xyz.lne.researchgroupmanage.controller.response.*;
import xyz.lne.researchgroupmanage.entity.*;
import xyz.lne.researchgroupmanage.exception.BadRequestException;
import xyz.lne.researchgroupmanage.mapper.*;
import xyz.lne.researchgroupmanage.service.ResearchService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.lne.researchgroupmanage.service.dataTransferObject.*;

import java.sql.SQLException;
import java.sql.Wrapper;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author team7
 * @since 2021-01-19
 */
@Service
public class ResearchServiceImpl extends ServiceImpl<ResearchMapper, Research> implements ResearchService {

    @Autowired
    private ResearchMapper researchMapper;

    @Autowired
    private UserResearchMapper userResearchMapper;

    @Autowired
    private DocumentMapper documentMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskUserMapper taskUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public List<ResearchSimpleDTO> findAllResearch() {
        QueryWrapper<Research> researchQueryWrapper = new QueryWrapper<>();
        researchQueryWrapper.eq("is_dissolve", 0);

        List<Research> researchs = researchMapper.selectList(researchQueryWrapper);

        List<SysUser> sysUsers = sysUserMapper.selectList(null);
        Map<Integer, String> id_name = new HashMap<>();
        sysUsers.forEach(sysUser -> {
            id_name.put(sysUser.getUserId(), sysUser.getName());
        });


        List<ResearchSimpleDTO> researchSimpleDTOS = new LinkedList<>();

        researchs.forEach(research -> {
            ResearchSimpleDTO researchSimpleDTO = new ResearchSimpleDTO();
            BeanUtils.copyProperties(research, researchSimpleDTO);
            researchSimpleDTO.setUserName(id_name.get(research.getUserId()));
            researchSimpleDTOS.add(researchSimpleDTO);
        });
        return researchSimpleDTOS;
    }

    @Override
    public List<ResearchSimpleDTO> findResearchBymanagerId(Integer userId) {
        List<ResearchSimpleDTO> researchSimpleDTOS = new LinkedList<>();

        QueryWrapper<Research> researchQueryWrapper = new QueryWrapper<>();

        researchQueryWrapper.eq("user_id", userId);
        researchQueryWrapper.eq("is_dissolve", 0);
        researchQueryWrapper.eq("is_hide", 0);

        List<SysUser> sysUsers = sysUserMapper.selectList(null);
        Map<Integer, String> id_name = new HashMap<>();
        sysUsers.forEach(sysUser -> {
            id_name.put(sysUser.getUserId(), sysUser.getName());
        });

        List<Research> researchs = researchMapper.selectList(researchQueryWrapper);

        researchs.forEach(research -> {
            ResearchSimpleDTO researchSimpleDTO = new ResearchSimpleDTO();
            BeanUtils.copyProperties(research, researchSimpleDTO);
            researchSimpleDTO.setUserName(id_name.get(research.getUserId()));
            researchSimpleDTOS.add(researchSimpleDTO);
        });

        return researchSimpleDTOS;
    }

    @Override
    public List<ResearchSimpleDTO> findResearchByuserId(Integer userId) {
        List<ResearchSimpleDTO> researchSimpleDTOS = new LinkedList<>();

        QueryWrapper<UserResearch> userResearchQueryWrapper = new QueryWrapper<>();
        userResearchQueryWrapper.eq("user_id", userId);

        List<UserResearch> userResearches = userResearchMapper.selectList(userResearchQueryWrapper);
        SysUser sysUser = sysUserMapper.selectById(userId);

        userResearches.forEach(userResearch -> {
            ResearchSimpleDTO researchSimpleDTO = new ResearchSimpleDTO();
            Research research = researchMapper.selectById(userResearch.getResearchId());
            BeanUtils.copyProperties(research, researchSimpleDTO);
            researchSimpleDTO.setUserName(sysUser.getName());
            researchSimpleDTOS.add(researchSimpleDTO);
        });

        return researchSimpleDTOS;
    }

    @Override
    public List<ResearchSimpleDTO> findResearchByResearchGroupId(Integer researchGroupId) {
        List<ResearchSimpleDTO> researchSimpleDTOS = new LinkedList<>();

        QueryWrapper<Research> researchQueryWrapper = new QueryWrapper<>();
        researchQueryWrapper.eq("researchgroup_id", researchGroupId);

        List<Research> researches = researchMapper.selectList(researchQueryWrapper);


        researches.forEach(research -> {
            ResearchSimpleDTO researchSimpleDTO = new ResearchSimpleDTO();
            BeanUtils.copyProperties(research, researchSimpleDTO);
            researchSimpleDTO.setUserName(sysUserMapper.selectById(research.getUserId()).getName());
            researchSimpleDTOS.add(researchSimpleDTO);
        });

        return researchSimpleDTOS;
    }

    @Override
    public ResearchSimpleDTO findSimpleResearchById(Integer researchId) {
        Research research = researchMapper.selectById(researchId);

        ResearchSimpleDTO researchSimpleDTO = new ResearchSimpleDTO();

        BeanUtils.copyProperties(research, researchSimpleDTO);

        return researchSimpleDTO;
    }

    @Override
    public ResearchDTO findResearchNormalById(Integer researchId) {
        Research research = researchMapper.selectById(researchId);

        if(research == null){
            Map<String, Object> e = new HashMap<>();
            e.put("该课题不存在", research.getResearchId());
            throw new BadRequestException(e);
        }

        if(research.getIsDissolve() == true){
            Map<String, Object> e = new HashMap<>();
            e.put("该课题已解散", research.getResearchId());
            throw new BadRequestException(e);
        }

        ResearchDTO researchDTO = new ResearchDTO();

        BeanUtils.copyProperties(research, researchDTO);

        QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.eq("research_id", research.getResearchId());

        QueryWrapper<TaskUser> taskUserQueryWrapper = new QueryWrapper<>();


        List<Task> tasks = taskMapper.selectList(taskQueryWrapper);

        List<TaskSimpleDTO> taskSimpleDTOS = new LinkedList<>();

        tasks.forEach(task -> {
            TaskSimpleDTO taskSimpleDTO = new TaskSimpleDTO();
            taskSimpleDTO.setCreateTime(task.getCreateTime());
            taskUserQueryWrapper.eq("task_id", task.getTaskId())
                                .eq("status", 1);
            taskSimpleDTO.setFinishPeopleNum(taskUserMapper.selectCount(taskUserQueryWrapper));
            taskSimpleDTO.setName(task.getName());
            taskSimpleDTO.setResearchName(research.getName());
            taskSimpleDTO.setTaskId(task.getTaskId());
            taskQueryWrapper.eq("task_id", task.getTaskId());
            taskSimpleDTO.setTotalPeopleNum(taskUserMapper.selectCount(taskUserQueryWrapper));
            taskSimpleDTOS.add(taskSimpleDTO);
        });

        researchDTO.setTaskSimpleDTOList(taskSimpleDTOS);

        List<DocumentSimpleDTO> documentSimpleDTOS = new LinkedList<>();

        QueryWrapper<Document> documentQueryWrapper = new QueryWrapper<>();
        documentQueryWrapper.eq("research_id", researchId);

        List<Document> documents = documentMapper.selectList(documentQueryWrapper);

        List<SysUser> sysUsers = sysUserMapper.selectList(null);
        Map<Integer, String> userid_name = new HashMap<>();
        sysUsers.forEach(sysUser -> {
            userid_name.put(sysUser.getUserId(), sysUser.getName());
        });

        documents.forEach(document -> {
            DocumentSimpleDTO documentSimpleDTO = new DocumentSimpleDTO();
            BeanUtils.copyProperties(document, documentSimpleDTO);
            documentSimpleDTOS.add(documentSimpleDTO);
        });

        researchDTO.setDocumentSimpleDTOList(documentSimpleDTOS);

        List<UserResearchDTO> userResearchDTOS = new LinkedList<>();

        QueryWrapper<UserResearch> userResearchQueryWrapper = new QueryWrapper<>();
        userResearchQueryWrapper.eq("research_id", researchId);

        List<UserResearch> userResearches = userResearchMapper.selectList(userResearchQueryWrapper);

        userResearches.forEach(userResearch -> {
            UserResearchDTO userResearchDTO = new UserResearchDTO();
            BeanUtils.copyProperties(userResearch, userResearchDTO);
            userResearchDTOS.add(userResearchDTO);
        });

        researchDTO.setUserResearchDTOList(userResearchDTOS);

        return  researchDTO;
    }

    @Override
    public ResearchDTO addResearch(Research research) {
        researchMapper.insert(research);

        ResearchDTO researchDTO = new ResearchDTO();

        BeanUtils.copyProperties(research, researchDTO);

        return researchDTO;
    }

    @Override
    public ResearchDTO updateResearch(Research research) {
        Research selectresearch = researchMapper.selectById(research);

        if(research == null){
            Map<String, Object> e = new HashMap<>();
            e.put("该课题不存在", research.getResearchId());
            throw new BadRequestException(e);
        }

        if(research.getIsDissolve() == true){
            Map<String, Object> e = new HashMap<>();
            e.put("该课题已解散", research.getResearchId());
            throw new BadRequestException(e);
        }

        researchMapper.updateById(research);

        ResearchDTO researchDTO = new ResearchDTO();
        BeanUtils.copyProperties(research, researchDTO);

        return researchDTO;
    }

    @Override
    public List<ResearchSimpleDTO> findResearchByKeyword(String Keyword) {
        List<ResearchSimpleDTO> researchSimpleDTOS = new LinkedList<>();

        QueryWrapper<Research> researchQueryWrapper = new QueryWrapper<>();
        researchQueryWrapper.like("name", Keyword);

        List<Research> researches = researchMapper.selectList(researchQueryWrapper);

        researches.forEach(research -> {
            ResearchSimpleDTO researchSimpleDTO = new ResearchSimpleDTO();
            BeanUtils.copyProperties(research, researchSimpleDTO);
            researchSimpleDTO.setUserName(sysUserMapper.selectById(research.getUserId()).getName());
            researchSimpleDTOS.add(researchSimpleDTO);
        });

        return researchSimpleDTOS;
    }

    @Override
    public List<UserResearchDTO> findAllResearchUsers(Integer researchId) {
        Research research = researchMapper.selectById(researchId);

        if(research == null){
            Map<String, Object> e = new HashMap<>();
            e.put("该课题不存在", researchId);
            throw new BadRequestException(e);
        }

        if(research.getIsDissolve() == true){
            Map<String, Object> e = new HashMap<>();
            e.put("该课题已解散", researchId);
            throw new BadRequestException(e);
        }

        QueryWrapper<UserResearch> userResearchQueryWrapper = new QueryWrapper<>();
        userResearchQueryWrapper.eq("research_id", researchId);

        List<UserResearch> userResearches = new LinkedList<>();
        userResearches = userResearchMapper.selectList(userResearchQueryWrapper);

        List<UserResearchDTO> userResearchDTOS = new LinkedList<>();

        userResearches.forEach(userResearch -> {
            UserResearchDTO userResearchDTO = new UserResearchDTO();
            BeanUtils.copyProperties(userResearch, userResearchDTO);
            userResearchDTOS.add(userResearchDTO);
        });

        return userResearchDTOS;
    }

    @Override
    public UserResearchDTO userApplyResearch(Integer userId, Integer researchId, String remark) {
        UserResearch userResearch = new UserResearch();
        userResearch.setApplyTime(new Date());
        userResearch.setResearchId(researchId);
        userResearch.setUserId(userId);
        userResearch.setRemark(remark);
        userResearch.setStatus(0);

        QueryWrapper<UserResearch> userResearchQueryWrapper = new QueryWrapper<>();
        userResearchQueryWrapper.eq("user_id", userId)
                                .eq("research_id", researchId);

        UserResearch selectUserResearch = userResearchMapper.selectOne(userResearchQueryWrapper);
        if (selectUserResearch == null) {
            Map<String, Object> e = new HashMap<>();
            e.put("已经加入该课题", researchId);
            throw new BadRequestException(e);
        }

        userResearchMapper.insert(userResearch);

        UserResearchDTO userResearchDTO = new UserResearchDTO();
        BeanUtils.copyProperties(userResearch, userResearchDTO);

        return userResearchDTO;
    }

    @Override
    public Boolean deleteResearch(Integer researchId) {
        if (researchMapper.selectById(researchId) == null) {
            Map<String, Object> e = new HashMap<>();
            e.put("删除的课题组不存在", researchId);
            throw new BadRequestException(e);
        }
        Research research = new Research();
        research.setResearchId(researchId);
        research.setIsDissolve(true);

        researchMapper.updateById(research);
        return true;
    }

}
